import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  // 取消上一个url的所有请求
  try {
    if (to.path !== from.path) {
      // 当to和from的path不一致时
      window.axiosPromiseArr.forEach((item) => {
        item.calcel();
      });
      window.axiosPromiseArr = [];
    }
  } catch (error) {
    console.log(error);
  }
  try {
    await store.dispatch("permission/generateRoutes", []);
  } catch (error) { console.log(error); }
  // 验证是否登录
  // TODO 此处不适用await ，会导致第一次进入不是/login时，hashchange事件检测不到
  if (store.state.user.loginFlag === 0 && to.path !== "/login") {
    await store.dispatch("user/checkLogin").then((res) => {
      store.dispatch("user/setInfo", {
        name: res.data.userName,
        roles: res.data.roles,
        role_id: res.data.roleId,
        buttons: res.data.buttons,
        id: res.data.id,
        userInfo: {
          id: String(res.data.id),
          userCode: res.data.userCode,
          userName: res.data.userName
        },
        userDept: (res.data.deptList || []).map((vo) => {
          return {
            id: vo.zzjgId,
            zzjg_code: vo.zzjgCode,
            zzjg_name: vo.zzjgName
          };
        })
      });
      NProgress.start();
      next();
    }).catch(() => {
      // next('/login')
      if (window.$loginUrl) {
        window.$toLoginFunc();
      } else {
        next("/login");
      }
    });
  } else {
    NProgress.start();
    next();
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
